# 贪吃蛇_kivy.py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.label import Label
import random

FPS = 3
SPEED = 40
WIDTH = Window.size[0]
HEIGHT = Window.size[1]

class MainBoard(Widget):
	head = [(WIDTH/2)//SPEED*SPEED, (HEIGHT/2)//SPEED*SPEED]
	body = [[(WIDTH/2)//SPEED*SPEED + SPEED,(HEIGHT/2)//SPEED*SPEED]]
	apples = []

	direction = "left"
	touchDown = []
	GameOver = False

	def on_touch_down(self,touch): #点击开始
		self.touchDown = [touch.pos[0],touch.pos[1]]

	def on_touch_up(self,touch): #点击结束
		hor = touch.pos[0] - self.touchDown[0] #水平方向的滑动
		ver = touch.pos[1] - self.touchDown[1] #竖直方向的滑动
		if abs(hor)>abs(ver):  #水平滑动
			if hor>0:
				self.direction = "right"
			else:
				self.direction = "left"
		else: #竖直滑动
			if ver>0:
				self.direction = "up"
			else:
				self.direction = "down"

	def createApple(self):
		while True:
			newApple = [random.randint(0,WIDTH-SPEED)//SPEED*SPEED,random.randint(0,HEIGHT-SPEED)//SPEED*SPEED]
			if newApple not in self.apples and newApple != self.head and newApple not in self.body:
				self.apples.append(newApple)
				break

	def update(self,dt):
		self.canvas.clear()
		self.clear_widgets()
		if self.GameOver:
			self.add_widget(Label(text="GameOver! score: %d"%(len(self.body)-1),pos=(WIDTH/3,HEIGHT/2),font_size=50))
		else:	
			self.body.insert(0,[self.head[0],self.head[1]])
			if self.direction=="left":
				self.head[0]-=SPEED
			elif self.direction=="right":
				self.head[0]+=SPEED
			elif self.direction=="up":
				self.head[1]+=SPEED
			elif self.direction=="down":
				self.head[1]-=SPEED
			if self.head[0]<0 or self.head[0]>WIDTH-SPEED or self.head[1]<0 or self.head[1]>HEIGHT-SPEED or self.head in self.body:
				self.GameOver = True
			if self.head not in self.apples:
				self.body.pop(-1)
			else:
				self.apples.remove(self.head)
				self.createApple()
			with self.canvas:
				Color(0.7, 0.7, 0.7)
				Rectangle(pos=self.head, size=(SPEED, SPEED))
			with self.canvas:
				Color(1, 1, 1)
				for i in self.body:
					Rectangle(pos=i, size=(SPEED, SPEED))
			with self.canvas:
				Color(1, 0, 0)
				for apple in self.apples:
					Rectangle(pos=apple, size=(SPEED,SPEED))


class SnakeApp(App):
	def build(self):
		board = MainBoard()
		board.createApple()
		Clock.schedule_interval(board.update,1/FPS)
		return board


SnakeApp().run()